package com.ruoyi.app.util;


import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class GsonUtil {
    private static final Gson gson = new GsonBuilder()
            .setDateFormat("yyyy-MM-dd HH:mm:ss") // 设置日期格式
            .create();

    public GsonUtil() {
    }

    public static String toJson(Object object) {
        return gson.toJson(object);
    }

    public static <T> T fromJson(JsonObject json, Class<T> clz) {
        return gson.fromJson(json, clz);
    }
    public static <T> T fromJsonByType(String json, Type clz) {
        return gson.fromJson(json, clz);
    }

    public static <T> T fromJson(String json, Class<T> clz) {
        return gson.fromJson(json, clz);
    }

    public static <T> List<T> jsonToList(String json, Class<T> clz) {
        Type type = (new TypeToken<List<T>>() {
        }).getType();
        return (List)gson.fromJson(json, type);
    }

    public static <T> List<T> fromJsonList(String json, Class<T> cls) {
        List<T> mList = new ArrayList();
        JsonArray array = (new JsonParser()).parse(json).getAsJsonArray();
        Gson mGson = new Gson();
        Iterator var5 = array.iterator();

        while(var5.hasNext()) {
            JsonElement elem = (JsonElement)var5.next();
            mList.add(mGson.fromJson(elem, cls));
        }

        return mList;
    }

    public static <T> List<Map<String, T>> toListMap(String json, Class<T> clz) {
        Type type = (new TypeToken<List<Map<String, T>>>() {
        }).getType();
        return (List)gson.fromJson(json, type);
    }

    public static <T> Map<String, T> toMap(String json, Class<T> clz) {
        Type type = (new TypeToken<Map<String, T>>() {
        }).getType();
        return (Map)gson.fromJson(json, type);
    }

    public static <T> Map<String, T> toMap(String json, TypeToken<Map<String, T>> typeToken) {
        return (Map)gson.fromJson(json, typeToken.getType());
    }

    public static <T> T toAny(String json, TypeToken<T> typeToken) {
        return gson.fromJson(json, typeToken.getType());
    }

    public static String transferStr(Object input) {
        if (input == null) {
            return null;
        } else {
            return !(input instanceof String) && !(input instanceof Integer) && !(input instanceof Boolean) ? gson.toJson(input) : String.valueOf(input);
        }
    }
}